<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>手写sleep函数</title>
  </head>
  <body>
    <script>
      const sleep = (n) => {
        let p;
        p = new Promise((resolve, reject) => {
          setTimeout(() => {
            // pending 等待
            console.log(p);
            reject();
            // fulfilled 成功
            // rejected 失败
            console.log(p);
          }, n);
          // if (!n) {
          //   reject("请传入参数");
          // }
        });
        return p;
      };

      sleep(3000)
        .then(() => {
          console.log("成功");
        })
        .catch((err) => {
          console.log("失败");
        })
        .finally(() => {
          // 无论失败或者成功 都会执行
          // promise 状态从pending到了 fullfilled 或 rejected
          console.log("finally");
        });
    </script>
  </body>
</html>
